// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: GPL-3.0-only

package service_cmd

import (
	"errors"
	"fmt"
	"os"
	"os/signal"
	"syscall"

	"gitcode.com/openseaotter/so_agent/config"
	"gitcode.com/openseaotter/so_agent/utils"
	"gitcode.com/openseaotter/so_agent/watch_impl"
	"github.com/spf13/cobra"
)

var runCmd = &cobra.Command{
	Use: "run",
	RunE: func(cmd *cobra.Command, args []string) error {
		_, err := config.ReadAgentConfigFromCache()
		if err != nil {
			return err
		}

		err = processPidFile()
		if err != nil {
			return err
		}

		defer os.Remove(utils.PID_FILE_PATH)

		exitChan := make(chan error, 10)
		//启动watch
		watchManager := watch_impl.NewWatchManager()
		err = watchManager.Reload()
		if err != nil {
			return err
		}
		go func() {
			sigChan := make(chan os.Signal, 1)
			signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGHUP)
			for {
				sig := <-sigChan
				if sig == syscall.SIGHUP {
					config.MarkServerConfigChange()
					watchManager.Reload() //skip error check
				} else {
					exitChan <- errors.New("catch signal")
				}
			}
		}()

		for {
			err = <-exitChan
			if err != nil {
				return err
			}
		}

	},
}

func processPidFile() error {
	oldPid, err := utils.LoadPid()
	if err == nil { //可能存在老进程
		p, _ := os.FindProcess(oldPid) //在linux上总是成功返回
		err = p.Signal(syscall.Signal(0))
		if err == nil { //存在老进程
			return fmt.Errorf("allread running")
		}
		os.Remove(utils.PID_FILE_PATH)
	}
	return utils.StorePid()
}
